// JavaScript Document
//viewModel
//----------------------Shripal 11 June 2013-------------------
var isHelpActive=false;
var baseurl="";
var mode="'edit'";
var items; //Declaring Items
var Gradeitems; //Declaring Grade
var SelectedGradeData; 
var isViewMode;
var isEditMode;
var SelectedClass
var gradeArr;
var publishData;
var getId;
var jsonDataStr="";
var assessmentid;
var selectedAssId;
var selectTabRef;
var visibleClose;
var msgText;
var sectionTitle="";
var currentGradeId="";
var onSubmit = false;
//
var selectedInd;
var aypId;
var _startDate;
var _endDate;

function loadScheduleData(){
		msgText("Loading Data...");
		showLoader(true, TYPE_LOADING);
		var urls=baseurl.replace("DUMMY","getSectionClassesBYSectionId");
	   jQuery.ajax({
		type : 'POST',
		url : urls, 
		success : parseScheduleJson,
		error : jsonIOError
		 });
	   
}

function parseScheduleJson(json)
{
	showLoader(false, TYPE_LOADING);
	json = sortByKey(json, 'gradeTitle');
	//console.log("===",json);
	for(var j=0;j<json.length;j++)
    { 
		gradeArr.push(new gradeData({ceGradeId:json[j].ceGradeId, gradeTitle:json[j].gradeTitle}));
    }
	SelectedClass(String(json[0].gradeTitle));
	getId(json[0].ceGradeId);
	loadSubjectData(json[0].ceGradeId);
}

function loadSubjectData(id){
  		currentGradeId = id;
		//
		var urls=baseurl.replace("DUMMY","getSecAssessments");
	   jQuery.ajax({
		type : 'POST',
		url :urls+"&ceGradeId="+id, 
		success : parseSubjectJson,
		error : jsonIOError
		 });
}
function parseSubjectJson(json)
{
	//console.log("==::==",json);
	json = sortByKey(json, 'assessmentId');
	jsonDataStr=json;
	dataHandler(json);
	SelectedGradeData([items()[0]]);
	count=0;
	getStatusForGrades();
	//console.log("SelectedGradeData.ceGradeId()=",SelectedGradeData()[0].ceGradeId());
	//setTimeout(setColors,100);
	//setColors()	
}

function getStatusForGrades(){
	 //
     console.log("getStatusForGrades:"+currentGradeId+":");
    //
	showLoader(true, TYPE_LOADING);
		var urls=baseurl.replace("DUMMY","getSecAssessmentsStatus");
	   jQuery.ajax({
		type : 'POST',
		url : urls, 
		url :urls+"&ceGradeId="+currentGradeId+"&sectionId="+sectionID, 
		success : setColors,
		error : jsonIOError
		 });
}

var count=0;

function setColors(data)
{
	//console.log("jsonDataStr",jsonDataStr.length);
	console.log("setColors:",data);
	var count=0;
	for(count=0;count<jsonDataStr.length;count++){
		for(var iloop=0;iloop<data.length;iloop++){
			//console.log("data[iloop].gradeClassId",data[iloop].assessmentId,"==",jsonDataStr[0].assessmentId);
			if((data[iloop].assessmentId==jsonDataStr[count].assessmentId) && (currentGradeId==data[iloop].gradeClassId)){
				console.log("String(data[iloop].planStatus)",String(data[iloop].planStatus));
				if(String(data[iloop].planStatus)=="0"){
					var obj1="#accordion #"+count;
					jQuery(obj1).css("background","none");
					break;
				}else if(String(data[iloop].planStatus)=="1"){
					var obj1="#accordion #"+count;
					jQuery(obj1).css("background","none");
					jQuery(obj1).css("backgroundColor","#ABEB8D");
					break;
				}else if(String(data[iloop].planStatus)=="2"){
					var obj2="#accordion #"+count;
					jQuery(obj2).css("background","none");
					jQuery(obj2).css("backgroundColor","#FFE191");
					break;
				}			
			}
		}

	}
	for(var i=0;i<SelectedGradeData()[0].tests().length;i++){
		if(String(selectedAssId)==String(SelectedGradeData()[0].tests()[i].assessmentId())){
			jQuery("#accordion").accordion({ active: i});
			selectTabRef=SelectedGradeData()[0].tests()[i];
			preRef=selectTabRef;
			prSubAssModel.selectedAccordian(SelectedGradeData()[0].tests()[i]);
			assessmentid(SelectedGradeData()[0].tests()[i].assessmentId());
			selectTabRef.saveAsDraftVisible(true);
			selectTabRef.saveVisible(true);
			loadTabData();
		}
	}
	
}

function loadTabData()
{
	var urls=baseurl.replace("DUMMY","getSecAssessmentTests");
	jQuery.ajax({
	type : 'POST',
	url :urls+"&ceGradeId="+getId()+"&assessmentId="+assessmentid(), 
	success : parseTabData,
	error : tabjsonIOError
	 });
}
function parseTabData(json)
{
	//console.log("schedule data :::==",json);
	jsonDataStr=json;
	accordionData();	
}
function savePrincipaldbAjax(datas){	
	showLoader(true, TYPE_SAVING);
	var urls=baseurl.replace("DUMMY","saveSecAssessmentTest");
	jQuery.ajax({
    url: urls,
    type: 'POST',      
    data: datas,   
    dataType: 'json',
    async: false,
    success: function(msg) {
		showLoader(false, TYPE_SAVING);		
		console.log("msg ::",msg);
		jQuery("#dialog-Errors-Tab2").dialog("open");
    }
    ,error : jsonIOError 		
	});
}
function sortByKey(array, key) {
    return array.sort(function(a, b) {
        var x = a[key]; var y = b[key];
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}
function jsonIOError(msg){alert("Error loading JSON!"+msg);}
function tabjsonIOError()
{
	visibleClose(true);
	msgText("Error in loading data..."); 
	//alert("Error loading JSON!");
}

function initialize(){ 
	
	//displayAttendance=false;
	//dialog-Errors-Tab2
	$("#dialog-Errors-Tab2").dialog({
		autoOpen : false,
		width : 420,
		modal : true
	});
	
  	ko.bindingHandlers.jqueryUIBindings = {
	
	init: function(element, valueAccessor) {
		// This will be called when the binding is first applied to an element
		// Set up any initial state, event handlers, etc. here
			var sd=String(_startDate).split("-");
			var ed=String(_endDate).split("-");
			var dt1=new Date(sd[0],sd[1],sd[2]);
			var dt2=new Date(ed[0],ed[1],ed[2]);
			
			//jQuery(".datepicker").datepicker("option", "minDate", dt1);
			//jQuery(".datepicker").datepicker("option", "maxDate", dt2);
			jQuery(element).datepicker({
				changeMonth: true,
				changeYear: true, 
				dateFormat: "dd-mm-yy",
				beforeShowDay : highlightDays,
				minDate:String(sd[2]+"-"+sd[1]+"-"+sd[0]),
				maxDate:String(ed[2]+"-"+ed[1]+"-"+ed[0])
			
			});
			
		
		},
		
		update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
		
		}
	
	};
	ko.bindingHandlers.jqueryUIBindingstimer = {
	
	init: function(element, valueAccessor) {
	
			jQuery(element).timepicker({
				hourGrid: 4,
				minuteGrid: 10,
				timeFormat: 'hh:mm tt'
			});
		
		},
		
		update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
		
		}
	
	};
	ko.bindingHandlers.jqueryUIBindingsduration = {
	
	init: function(element, valueAccessor) {
		// This will be called when the binding is first applied to an element
		// Set up any initial state, event handlers, etc. here
			jQuery(element).timepicker({
				hourMin: 0,
				hourMax: 24
			});
		
		},
		
		update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
		
		}
	
	};
	
	
	prSubAssModel=new initBinding()
	ko.applyBindings(prSubAssModel);
	loadScheduleData();
	

	  
}
var prSubAssModel
var jsonString='[{"assessmentId":"SA1","classId":"1","testDate":"11-06-2013","weight":"30","testStatus":"not schedule", "childs":[{"subject":"English","testDate":"11-06-2013","startTime":"", "evmr":"PM", "durationH":"", "durationM":"","totalMarks":"100","childs":[]},{"subject":"History","testDate":"11-06-2013","startTime":"", "evmr":"PM","durationH":"", "durationM":"","totalMarks":"100","childs":[]},{"subject":"Hindi","testDate":"11-06-2013","startTime":"", "evmr":"PM","durationH":"", "durationM":"","totalMarks":"100","childs":[]}]},{"assessmentId":"SA2","classId":"2","testDate":"11-06-2013","weight":"30","testStatus":"not schedule","childs":[{"subject":"English","testDate":"11-06-2013","startTime":"", "evmr":"PM","durationH":"", "durationM":"","totalMarks":"100","childs":[]},{"subject":"History","testDate":"11-06-2013","startTime":"", "evmr":"PM","durationH":"", "durationM":"","totalMarks":"100","childs":[]},{"subject":"Hindi","testDate":"11-06-2013","startTime":"", "evmr":"PM","durationH":"", "durationM":"","totalMarks":"100","childs":[{"subject":"Hindi Grammer","testDate":"11-06-2013","startTime":"", "evmr":"PM","durationH":"", "durationM":"","totalMarks":"100","childs":[]},{"subject":"Hindi Writing","testDate":"11-06-2013","startTime":"", "evmr":"PM","durationH":"", "durationM":"","totalMarks":"100","childs":[]}]}]}]';
function initBinding()
{
	
	var self=this;
	items=ko.observableArray([new gradeData({ceGradeId:"",gradeTitle:"", tests:[]})]);
	SelectedClass=ko.observable("Class 1");
	getId=ko.observable("Class 1");
	assessmentid=ko.observable("Class 1");
	msgText=ko.observable("Loading Data...");
	gradeArr=ko.observableArray([new gradeData({ceGradeId:"",gradeTitle:"", tests:[]})]);
	gradeArr.removeAll();
	var parsed = jQuery.parseJSON(jsonString);
	SelectedGradeData=ko.observableArray([items()[0]]);	
	visibleClose=ko.observable(false);
	publishData=ko.observable("1");
	self.selectedAccordian=ko.observable();
	isEditMode=ko.computed(function(){
		if(String(mode) == "edit"){
			return true;
		}else{
			return false;
		}
	},this)
	selectGrade=function(data,event){
		showLoader(false, TYPE_LOADING);
		var name = ko.utils.unwrapObservable(data.gradeTitle); 
		SelectedClass(name); 
		var id = ko.utils.unwrapObservable(data.ceGradeId);
		getId(id);
		loadSubjectData(id);
	}
	
	saveData=function()
	{
		console.log("##SAVE DATA IS CALLED##");
		//$("#accordion").accordion({event: false});		
		    onSubmit=true;
			var vm = ko.validation.group(self.selectedAccordian());
		
			console.log("##self.selectedAccordian().tests().length##",self.selectedAccordian().tests().length);
			
				for(var r=0; r< self.selectedAccordian().tests().length;r++){
					if(self.selectedAccordian().tests()[r].tests().length > 0){
						for(var s=0; s< self.selectedAccordian().tests()[r].tests().length;s++){
							if(self.selectedAccordian().tests()[r].tests()[s].testDateValid())
							{
								//alert("Please fill all Required fields before saving==1.");
								msgText(selectTabRef.assessmentTitle()+" Test date not valid.");
								jQuery("#dialog-Errors-Tab2").dialog('option', 'title', 'Message');
								jQuery("#dialog-Errors-Tab2").dialog("open");
								return;
							}
							if(self.selectedAccordian().tests()[r].tests()[s].startTimesvalid())
							{
								//alert("Please fill all Required fields before saving==2.");
								msgText(selectTabRef.assessmentTitle()+" Start time not valid.");
								jQuery("#dialog-Errors-Tab2").dialog('option', 'title', 'Message');
								jQuery("#dialog-Errors-Tab2").dialog("open");
								return;
							}
							if(self.selectedAccordian().tests()[r].tests()[s].durationvalid())
							{
								msgText(selectTabRef.assessmentTitle()+" Test duration not valid.");
								jQuery("#dialog-Errors-Tab2").dialog('option', 'title', 'Message');
								jQuery("#dialog-Errors-Tab2").dialog("open");
								//alert("Please fill all Required fields before saving==3.");
								return;
							}
							if(Number(self.selectedAccordian().tests()[r].tests()[s].testTotalMarks()) < 1)
							{
								msgText(selectTabRef.assessmentTitle()+" Total marks should be greater than 0.");
								jQuery("#dialog-Errors-Tab2").dialog('option', 'title', 'Message');
								jQuery("#dialog-Errors-Tab2").dialog("open");
								return;
							}	
													
						}
					}else{
						var vm1 = ko.validation.group(self.selectedAccordian().tests()[r]);
						if(self.selectedAccordian().tests()[r].testDateValid())
						{
							//alert("Please fill all Required fields before saving==4.");
							msgText(selectTabRef.assessmentTitle()+" Test date not valid.");
							jQuery("#dialog-Errors-Tab2").dialog('option', 'title', 'Message');
							jQuery("#dialog-Errors-Tab2").dialog("open");
							return;
						}
						if(self.selectedAccordian().tests()[r].startTimesvalid())
						{
							//alert("Please fill all Required fields before saving==5.");
							msgText(selectTabRef.assessmentTitle()+" Start time not valid.");
							jQuery("#dialog-Errors-Tab2").dialog('option', 'title', 'Message');
							jQuery("#dialog-Errors-Tab2").dialog("open");
							return;
						}
						if(self.selectedAccordian().tests()[r].durationvalid())
						{
							msgText(selectTabRef.assessmentTitle()+" Test duration not valid.");
							jQuery("#dialog-Errors-Tab2").dialog('option', 'title', 'Message');
							jQuery("#dialog-Errors-Tab2").dialog("open");
							//alert("Please fill all Required fields before saving==6.");
							return;
						}
						if(Number(self.selectedAccordian().tests()[r].testTotalMarks()) < 1)
						{
							msgText(selectTabRef.assessmentTitle()+" Total marks should be greater than 0.");
							jQuery("#dialog-Errors-Tab2").dialog('option', 'title', 'Message');
							jQuery("#dialog-Errors-Tab2").dialog("open");
							return;
						}
					}
				}
				console.log("After all checkings");
			//}
		//self.selectedAccordian().statusPlan("1");
		selectTabRef.statusPlan("1");
		
		var mapping={
			'ignore' : ["saveVisible","saveAsDraftVisible", "aindex","startTimesvalid","testDateValid","evmr","startTimes","durationH","durationM","totalTime","ampm","comStartTime", "termStatus", "statusText", "errors", "openOnce", "assessmentTitle_t", "termTitle_t", "assessmentWindow_t","testDateSave","durationvalid","isEdit"]
			}
		var arr=new Array(self.selectedAccordian());
		var copy = ko.mapping.toJS(arr,mapping);
		var dataArr ={savedata: String(JSON.stringify(copy))}
		console.log(dataArr);
		msgText(selectTabRef.assessmentTitle()+" Publish data successfully.");
		jQuery("#dialog-Errors-Tab2").dialog('option', 'title', 'Publish');
		var obj="#accordion #"+Number(selectTabRef.aindex());
		jQuery(obj).css("background","none");
		jQuery(obj).css("backgroundColor","#ABEB8D");
		savePrincipaldbAjax(dataArr);
		return copy;
	}
	saveAsDraft=function()
	{
			var vm = ko.validation.group(self.selectedAccordian());
		
			console.log("##self.selectedAccordian().tests().length##",self.selectedAccordian().tests().length);
			
				for(var r=0; r< self.selectedAccordian().tests().length;r++){
					if(self.selectedAccordian().tests()[r].tests().length > 0){
						for(var s=0; s< self.selectedAccordian().tests()[r].tests().length;s++){
							if(self.selectedAccordian().tests()[r].tests()[s].testDateValid())
							{
								//alert("Please fill all Required fields before saving==1.");
								msgText(selectTabRef.assessmentTitle()+" Test date not valid.");
								jQuery("#dialog-Errors-Tab2").dialog('option', 'title', 'Message');
								jQuery("#dialog-Errors-Tab2").dialog("open");
								return;
							}
							if(self.selectedAccordian().tests()[r].tests()[s].startTimesvalid())
							{
								//alert("Please fill all Required fields before saving==2.");
								msgText(selectTabRef.assessmentTitle()+" Start time not valid.");
								jQuery("#dialog-Errors-Tab2").dialog('option', 'title', 'Message');
								jQuery("#dialog-Errors-Tab2").dialog("open");
								return;
							}
							if(self.selectedAccordian().tests()[r].tests()[s].durationvalid())
							{
								msgText(selectTabRef.assessmentTitle()+" Test duration not valid.");
								jQuery("#dialog-Errors-Tab2").dialog('option', 'title', 'Message');
								jQuery("#dialog-Errors-Tab2").dialog("open");
								//alert("Please fill all Required fields before saving==3.");
								return;
							}
							if(Number(self.selectedAccordian().tests()[r].tests()[s].testTotalMarks()) < 1)
							{
								msgText(selectTabRef.assessmentTitle()+" Total marks should be greater than 0.");
								jQuery("#dialog-Errors-Tab2").dialog('option', 'title', 'Message');
								jQuery("#dialog-Errors-Tab2").dialog("open");
								return;
							}	
													
						}
					}else{
						var vm1 = ko.validation.group(self.selectedAccordian().tests()[r]);
						if(self.selectedAccordian().tests()[r].testDateValid())
						{
							//alert("Please fill all Required fields before saving==4.");
							msgText(selectTabRef.assessmentTitle()+" Test date not valid.");
							jQuery("#dialog-Errors-Tab2").dialog('option', 'title', 'Message');
							jQuery("#dialog-Errors-Tab2").dialog("open");
							return;
						}
						if(self.selectedAccordian().tests()[r].startTimesvalid())
						{
							//alert("Please fill all Required fields before saving==5.");
							msgText(selectTabRef.assessmentTitle()+" Start time not valid.");
							jQuery("#dialog-Errors-Tab2").dialog('option', 'title', 'Message');
							jQuery("#dialog-Errors-Tab2").dialog("open");
							return;
						}
						if(self.selectedAccordian().tests()[r].durationvalid())
						{
							msgText(selectTabRef.assessmentTitle()+" Test duration not valid.");
							jQuery("#dialog-Errors-Tab2").dialog('option', 'title', 'Message');
							jQuery("#dialog-Errors-Tab2").dialog("open");
							//alert("Please fill all Required fields before saving==6.");
							return;
						}
						if(Number(self.selectedAccordian().tests()[r].testTotalMarks()) < 1)
						{
							msgText(selectTabRef.assessmentTitle()+" Total marks should be greater than 0.");
							jQuery("#dialog-Errors-Tab2").dialog('option', 'title', 'Message');
							jQuery("#dialog-Errors-Tab2").dialog("open");
							return;
						}
					}
				}
		
		
		selectTabRef.statusPlan("2")
		var obj="#accordion #"+Number(selectTabRef.aindex());
		jQuery(obj).css("background","none");
		jQuery(obj).css("backgroundColor","#FFE191");
		
		var mapping={
			'ignore' : ["saveVisible","saveAsDraftVisible", "aindex","startTimesvalid","testDateValid","evmr","startTimes","durationH","durationM","totalTime","ampm","comStartTime", "termStatus", "statusText", "errors", "openOnce", "assessmentTitle_t", "termTitle_t", "assessmentWindow_t","testDateSave","durationvalid","isEdit"]
			}
		
		var arr=new Array(self.selectedAccordian());
		//arr.push()
		var copy = ko.mapping.toJS(arr,mapping);
		var dataArr ={savedata: String(JSON.stringify(copy))}
		console.log("<------------------------------------------>");
		console.log(dataArr);
		
		msgText(selectTabRef.assessmentTitle()+" Save as draft data successfully.");
		jQuery("#dialog-Errors-Tab2").dialog('option', 'title', 'Save as draft');
		savePrincipaldbAjax(dataArr);
    	return copy;
	}
	closeErrorPopup=function()
	{
		visibleClose(false);
		showLoader(false, TYPE_LOADING);
	}
	self.clickBack=function()
	{
		//console.log("Back button clicked ::");
		location.href = baseurl.replace("p_p_state=exclusive","p_p_state=normal").replace("DUMMY","getAcademics");
	}
	/* Custom Binding for Date Picker */ 
}

function dataHandler(parsed)
{
	//console.log("jsonString===:::",parsed)
	parsed=jsonDataStr;
	parsed = sortByKey(parsed, 'startDate');
	items.removeAll();

		var gradeChildArr=new Array();
		
			for(var j=0;j<parsed.length;j++)
			{
				var darr=String(parsed[j].assessmentWindow).split("to")
				var stDate=String(darr[0]).split("-");
				var enDate=String(darr[1]).split("-");
				stDate[2]=String(stDate[2]).replace(" ","");
				enDate[0]=String(enDate[0]).replace(" ","");
				var sd=String(stDate[2]+"-"+stDate[1]+"-"+stDate[0]);
				var ed=String(enDate[2]+"-"+enDate[1]+"-"+enDate[0]);
				var assd=sd+" to "+ed				
				gradeChildArr.push(new dataTable({aindex:j,assessmentId:parsed[j].assessmentId, assessmentTitle:parsed[j].assessmentTitle, assessmentType:parsed[j].assessmentType, assessmentWindow:assd, endDate:parsed[j].endDate, reportlock:parsed[j].reportlock, sectionId:parsed[j].sectionId, startDate:parsed[j].startDate, termId:parsed[j].termId, termTitle:parsed[j].termTitle, weightage:parsed[j].weightage, statusPlan:parsed[j].statusPlan,tests:[]}));
				//console.log("statusPlan:parsed["+j+"].statusPlan",parsed[j].statusPlan);
			}
	items.push(new gradeData({ceGradeId:"",gradeTitle:"", tests:gradeChildArr}));
	
	// $("#accordion").accordion({ disabled: true });
}

function accordionData()
{
	var subjectChildArr=new Array();
	var parsed=jsonDataStr;
	console.log("parsed",parsed);
	//console.log("parsed===",parsed.length)
	for(var k=0;k<parsed.length;k++)
	{
		//console.log("st1===");
		var subSubjectChildArr=new Array();
		if(parsed[k].tests)
		{
			for(var m=0;m<parsed[k].tests.length;m++)
			{
				var st1=parsed[k].tests[m].testStartTime;
				if(!st1){st1="";}
				var dt1=parsed[k].tests[m].duration;
				if(!dt1){dt1="00:00";}
				
				
				var clId_s=getId();
				var salebus_s=parsed[k].tests[m].syllabus;
				if(!salebus_s){salebus_s=""}
				var techID_s=parsed[k].tests[m].techniqueId;
				if(!techID_s){techID_s=""}
				
				var testDt_s=parsed[k].tests[m].testDate;
				if(!testDt_s){testDt_s=""}
				
				var testID_s=parsed[k].tests[m].testId;
				if(!testID_s){testID_s=""}
				
				var toolID_s=parsed[k].tests[m].toolId;
				if(!toolID_s){toolID_s=""}
				
				subSubjectChildArr.push(new subSubjectTable({assessmentId:parsed[k].tests[m].assessmentId, toolId:toolID_s, testStatus:parsed[k].tests[m].testStatus, testId:testID_s, techniqueId:techID_s, syllabus:salebus_s, subjectId:parsed[k].tests[m].subjectId, gradelock:parsed[k].tests[m].gradelock, gradeClassId:clId_s, subjectTitle:parsed[k].tests[m].subjectTitle, testDate:testDt_s, testStartTime:st1, duration:dt1,testTotalMarks:parsed[k].tests[m].testTotalMarks, tests:[]}));
			}
		}
		var st=parsed[k].testStartTime;		
		if(!st){st=""}
		var dt=parsed[k].duration;
		if(!dt){dt="00:00";}
		
		var clId=getId();
		var salebus=parsed[k].syllabus;
		if(!salebus){salebus=""}
		var techID=parsed[k].techniqueId;
		if(!techID){techID=""}
		
		var testDt=parsed[k].testDate;
		if(!testDt){testDt=""}
		
		var testID=parsed[k].testId;
		if(!testID){testID=""}
		
		var toolID=parsed[k].toolId;
		if(!toolID){toolID=""}
		
		subjectChildArr.push(new scheduleTable({assessmentId:parsed[k].assessmentId, toolId:toolID, testStatus:parsed[k].testStatus, testId:testID, techniqueId:techID, syllabus:salebus, subjectId:parsed[k].subjectId, gradelock:parsed[k].gradelock, gradeClassId:clId, subjectTitle:parsed[k].subjectTitle, testDate:testDt, testStartTime:st, duration:dt,testTotalMarks:parsed[k].testTotalMarks, tests:subSubjectChildArr}))
	}
	selectTabRef.tests(subjectChildArr);
	selectTabRef.openOnce(true);
	visibleClose(false);
	showLoader(false, TYPE_LOADING);
}

function gradeData(data)
{
	var self=this;
	self.ceGradeId = ko.observable(data.ceGradeId);
	self.gradeTitle = ko.observable(data.gradeTitle);
	self.tests = ko.observableArray(data.tests);
}
var preRef;
function dataTable(data) {
	var self=this;
	self.assessmentId = ko.observable(data.assessmentId);
	self.isEdit = ko.observable(false);
	self.aindex=ko.observable(data.aindex);
	self.assessmentTitle = ko.observable(data.assessmentTitle);
	self.assessmentTitle_t=ko.observable(truncateText(data.assessmentTitle, 8));
	
	self.assessmentType = ko.observable(data.assessmentType);
	self.assessmentWindow = ko.observable(data.assessmentWindow);
	self.assessmentWindow_t = ko.observable(truncateText(data.assessmentWindow, 24));
	
	self.statusPlan = ko.observable(data.statusPlan);
	self.statusPlan.subscribe(function(newValue){
		self.statusText();
	},this)
	self.statusText=ko.computed(function(){ 
		var val="Not scheduled"; 
		if(String(self.statusPlan())==="1")
		{
			val="Scheduled"
		}; 
		if(String(self.statusPlan())==="2"){
			val="Draft"
		}; 
		return val;
	},this);
	self.endDate = ko.observable(data.endDate);
	self.reportlock = ko.observable(data.reportlock);
	self.sectionId = ko.observable(data.sectionId);
	self.startDate = ko.observable(data.startDate);
	self.termId = ko.observable(data.termId);
	self.termTitle = ko.observable(data.termTitle);
	self.termTitle_t= ko.observable(truncateText(data.termTitle, 8));
	
	self.weightage = ko.observable(data.weightage);
	self.tests = ko.observableArray(data.tests);
	self.openOnce=ko.observable(false);
	self.saveAsDraftVisible=ko.observable(false);
	self.saveVisible=ko.observable(false);
	self.clickTab=function(){
		//$("#accordion").accordion('activate', 1);
		//jQuery("#accordion").accordion({event: true});
		//var darr=String(parsed[j].assessmentWindow).split("to")
		//darr[0]=String(darr[0]).replace(" ","");
		//darr[1]=String(darr[1]).replace(" ","");
		//var s1=String().split("-")	
		
		preRef=selectTabRef;
		selectTabRef=self;
		if(!self.openOnce()){
			prSubAssModel.selectedAccordian(self);
			assessmentid(self.assessmentId());
			loadTabData();
			msgText("Loading Data...");
			showLoader(true, TYPE_LOADING);
			//console.log("here------");
		}
		if(String(selectTabRef.aindex()) != String(preRef.aindex())){
			self.saveAsDraftVisible(true);
			self.saveVisible(true);
			preRef.saveAsDraftVisible(false);
			preRef.saveVisible(false);
		}else
		{
			if(selectTabRef.saveAsDraftVisible())
			{
				selectTabRef.saveAsDraftVisible(false);
			}else
			{
				selectTabRef.saveAsDraftVisible(true);
			}
			if(selectTabRef.saveVisible())
			{
				selectTabRef.saveVisible(false);
			}else
			{
				selectTabRef.saveVisible(true);
			}
		}
	}
}

/*$('#accordion h3').bind('accordionchange', 
    function() {
    	console.log("=====================")
        // alert('Active tab index: ' + $(this).accordion('option', 'active'))
    });*/
//$( '#accordion' ).accordion({  activate: function( event, ui ) {console.log("accordion=======")}}); 

function scheduleTable(data)
{

	var self=this;

	self.assessmentId = ko.observable(data.assessmentId);
	self.gradeClassId = ko.observable(data.gradeClassId);
	self.gradelock = ko.observable(data.gradelock);
	self.subjectId = ko.observable(data.subjectId);
	self.subjectTitle = ko.observable(data.subjectTitle);
	self.syllabus = ko.observable(data.syllabus);
	self.techniqueId = ko.observable(data.techniqueId);
	self.testId = ko.observable(data.testId);
	self.testStatus = ko.observable(data.testStatus);
	self.toolId = ko.observable(data.toolId);
	console.log("data.testDate--->",data.testDate);
	var datFor=	String(data.testDate).split("-");
	if(datFor.length < 2)
	{
		var dt=new Date();
		if(dt.getDate()<=9){
			datFor[2]="0"+dt.getDate();
		}else{
			datFor[2]=dt.getDate();
		}
		if(dt.getMonth()<9){
			datFor[1]="0"+(dt.getMonth()+1);
		}else{
			datFor[1]=dt.getMonth()+1;
		}
		datFor[0]=dt.getFullYear();
	datFor[2]="";
	datFor[1]="";
	datFor[0]="";		
	}

   	self.testDateSave = ko.observable(datFor[2]+"-"+datFor[1]+"-"+datFor[0]).extend({required:true});
   	self.testDateValid=ko.computed(function(){
   		//var isval=true;
   		var isval=false;
   		/*if(validateMonths(self.testDateSave())){
				isval=false;
		}*/
   		return isval;
   	},this);
   	self.testDate = ko.computed(function(){
   		var datFor1=	String(self.testDateSave()).split("-");
   		return (datFor1[2]+"-"+datFor1[1]+"-"+datFor1[0])
   	},this);
	self.testTotalMarks = ko.observable(data.testTotalMarks).extend({required:true, min:1, max:999});
	self.tests = ko.observableArray(data.tests);
	
	var st=String(data.testStartTime).split(".");
	self.evmr = ko.observable(st[2]);
	//console.log("data.testStartTime===",data.testStartTime);
	self.startTimes = ko.observable(data.testStartTime);
	
	self.startTimesvalid=ko.computed(function(){
		var val=false;
		var val1;
		val1=validateTime1(self.startTimes());
		if(val1==false)
		{
			val=true;
		}
		return val;
	},this);
	
	
	self.testStartTime = ko.computed(function(){ return (self.startTimes())},this);
	var duh=String(data.duration).split(".");
	self.durationH = ko.observable(duh[0]);
	self.durationM = ko.observable(duh[1]);
	self.duration = ko.observable(data.duration).extend({required:true});
	self.durationvalid=ko.computed(function(){
		var val=false;
		var val1=validateTime(self.duration());
		if(val1==false)
		{
			val=true;
		}
		return val;
	},this);
	self.totalTime = ko.computed(function() {
       return self.durationH() + "." + self.durationM()+"hrs";  
    }, this);
	self.ampm=function(data1,data){ this.evmr(data1);}
	self.comStartTime=ko.computed(function(){return self.startTimes()+"."+self.evmr(); },this);
	/*ko.validation.rules['mustEqual'] = {
		validator: function (val, otherVal) {
			var v1=String(val).split(".");
			var v2=String(otherVal).split(".");
			return v1.length===v2.length;
		},
		message: ''
	};
	ko.validation.rules['hourVal'] = {
		validator: function (val, otherVal) {
			return String(val) === String(otherVal);
		},
		message: 'Not valid time'
	};
	ko.validation.rules['minVal'] = {
		validator: function (val, otherVal) {
			return val >= otherVal;
		},
		message: ''
	};
	ko.validation.rules['dateval'] = {
		validator: function (val, otherVal) {
			var isval="false";
			if(validateMonths(val)){
				isval="true";
			}
			console.log(isval,"==subject==",otherVal);
			return isval === otherVal;
		},
		message: 'Invalid date.'
	};*/
	ko.validation.registerExtenders();
}
function subSubjectTable(data) {
	var self=this;
	self.assessmentId = ko.observable(data.assessmentId);
	self.gradeClassId = ko.observable(data.gradeClassId);
	self.gradelock = ko.observable(data.gradelock);
	self.subjectId = ko.observable(data.subjectId);
	self.subjectTitle = ko.observable(data.subjectTitle);
	self.syllabus = ko.observable(data.syllabus);
	self.techniqueId = ko.observable(data.techniqueId);
	self.testId = ko.observable(data.testId);
	self.testStatus = ko.observable(data.testStatus);
	self.toolId = ko.observable(data.toolId);
	var datFor=	String(data.testDate).split("-");
	if(datFor.length < 2)
	{
		var dt=new Date();
		datFor[2]=dt.getDate();
		datFor[1]=dt.getMonth()+1;
		datFor[0]=dt.getFullYear();
	}
   	self.testDateSave = ko.observable(datFor[2]+"-"+datFor[1]+"-"+datFor[0]).extend({required:true});
   	self.testDateValid=ko.computed(function(){
   		//var isval=true;
   		var isval=false;
   		/*if(validateMonths(self.testDateSave())){
				isval=false;
		}*/
   		return isval;
   	},this);
   	self.testDate = ko.computed(function(){
   		var datFor1=	String(self.testDateSave()).split("-");
   		return (datFor1[2]+"-"+datFor1[1]+"-"+datFor1[0])
   	},this);
	
	self.testTotalMarks = ko.observable(data.testTotalMarks).extend({required:true, min:1, max:999});
	self.tests = ko.observableArray(data.tests);
	
	var st=String(data.testStartTime).split(".");
	self.evmr = ko.observable(st[2]);
	self.startTimes = ko.observable(data.testStartTime).extend({required:true});
	self.startTimesvalid=ko.computed(function(){
		var val=false;
		var val1=validateTime1(self.startTimes());
		if(val1==false)
		{
			val=true;
		}
		return val;
	},this);
	self.testStartTime = ko.computed(function(){ return (self.startTimes())},this);
	
	var duh=String(data.duration).split(".");
	self.durationH = ko.observable(duh[0]);
	self.durationM = ko.observable(duh[1]);
	self.duration = ko.observable(data.duration).extend({required:true});
	self.durationvalid=ko.computed(function(){
		var val=false;
		var val1=validateTime(self.duration());
		if(val1==false)
		{
			val=true;
		}
		return val;
	},this);
	self.totalTime = ko.computed(function() {
        return self.durationH() + "." + self.durationM()+"hrs";    
    }, this);
	self.ampm=function(data1,data){ self.evmr(data1);}
	self.comStartTime=ko.computed(function(){return self.startTimes()+"."+self.evmr();},this)
	/*ko.validation.rules['mustEqual'] = {
		validator: function (val, otherVal) {
			var v1=String(val).split(".");
			var v2=String(otherVal).split(".");
			return v1.length===v2.length;
		},
		message: 'Value must equal'
	};
	ko.validation.rules['hourVal'] = {
		validator: function (val, otherVal) {
			//var val1=validateTime(val);
			return String(val) === String(otherVal);
		},
		message: 'Not valid time'
	};
	ko.validation.rules['minVal'] = {
		validator: function (val, otherVal) {
			return val >= otherVal;
		},
		message: ''
	};
	ko.validation.rules['dateval'] = {
		validator: function (val, otherVal) {
			var isval="false";
			if(validateMonths(val)){
				isval="true";
			}
			console.log(val,"==sub subject==",otherVal);
			return isval === otherVal;
		},
		message: 'Invalid date'
	};*/
	ko.validation.registerExtenders();
	
}
function validateTime(s) {
  var t = s.split(':');
	if(String(s)=="00:00")
	{
		return false;
	}
  /*return /^\d\d:\d\d:\d\d$/.test(s) &&
         t[0] >= 0 && t[0] < 25 &&
         t[1] >= 0 && t[1] < 60 &&
         t[2] >= 0 && t[2] < 60;*/
   return /^\d\d:\d\d$/.test(s) &&
         t[0] >= 0 && t[0] < 25 &&
         t[1] >= 0 && t[1] < 60;
}
function validateTime1(s){
  var act=s.split(' ');
  var t = act[0].split(':');
	if(String(s)=="00:00")
	{
		return false;
	}
  /*return /^\d\d:\d\d:\d\d$/.test(s) &&
         t[0] >= 0 && t[0] < 25 &&
         t[1] >= 0 && t[1] < 60 &&
         t[2] >= 0 && t[2] < 60;*/
   return /^\d\d:\d\d$/.test(act[0]) &&
         t[0] >= 0 && t[0] < 25 &&
         t[1] >= 0 && t[1] < 60;
}
function validateMonths(leaveDate)
{
	var dtarr=String(leaveDate).split("-");
	
	 var todayDate = new Date();
	var selectedDate=new Date(dtarr[2],(dtarr[1]-1),dtarr[0]);
	 var month = todayDate.getMonth();
	 var day = todayDate.getDate();
	 var year = todayDate.getFullYear();
	 //var boundryDate = new Date(year,(month + 1), day);
	 //var boundryDate1 = new Date(year,(month - 1), day);
	 var boundryDate = new Date(year,month, (day+30));
	 var boundryDate1 = new Date(year,month, (day-30));
	 if (selectedDate > boundryDate){
	 return false; 
	}
	if (selectedDate < boundryDate1){
	 return false; 
	}	
	 return true;
}
function truncateText(_txt, num)
{
	var shortText
	if(_txt.length > num){
	 shortText= jQuery.trim(String(_txt)).substring(0, num);
	shortText=shortText+"..."
	} else
	{
		shortText=_txt;
	}
	return shortText;
}
function closeDialog()
{
	jQuery("#dialog-Errors-Tab2").dialog("close");
}

	ko.bindingHandlers.stopBinding = {
		init: function() {
		return { controlsDescendantBindings: true };
		}
	};

	ko.virtualElements.allowedBindings.stopBinding = true;
//	<!-- -----------------------Binding For Accordian--------------------------- -->
	
	ko.bindingHandlers.jqAccordion = {    
		init: function (element, valueAccessor) {   
			
			var options         = valueAccessor(),    
			accordianOptions    = options.options;    
			jQuery(element).accordion({heightStyle: "content"});
			jQuery(element).accordion(accordianOptions);
			
			jQuery(element).bind("valueChanged", function () {
	
				ko.bindingHandlers.jqAccordion.update(element, valueAccessor);    
			});
			
			//jQuery("h3").click(function (event){alert("==",event)});
		},
		update: function (element, valueAccessor) {
			var options = valueAccessor(),
				accordianOptions = options.options,
				dependency = ko.utils.unwrapObservable(options.updateOn);
			jQuery(element).accordion('destroy').accordion(accordianOptions);
		}
	};   

  




ko.bindingHandlers.spinner = {
    init: function (element, valueAccessor, allBindingsAccessor) {
		//if (Modernizr.inputtypes.number) {
		//ko.bindingHandlers.value.update.apply(null, arguments);
        //} else {
			var value = ko.utils.unwrapObservable(valueAccessor());
            //initialize spinner with some optional options
            var options = allBindingsAccessor().spinnerOptions || {};
            jQuery(element).spinner(options);
            //handle the field changing
            jQuery(element).on("spinstop", function () {
                var observable = valueAccessor();
                observable(jQuery(element).spinner("value"));
            });
            
            //handle disposal
            ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                jQuery(element).off("spinstop");
                jQuery(element).spinner("destroy");
            });
		//}
        
    },
    update: function (element, valueAccessor, allBindingsAccessor) {
       //if (Modernizr.inputtypes.number) {
         //   ko.bindingHandlers.value.update.apply(null, arguments);
        //} else {
            var value = ko.utils.unwrapObservable(valueAccessor());
            
            var disable = allBindingsAccessor().disable;
            
            if (typeof disable !== "undefined") {
                jQuery(element).spinner((disable) ? "disable" : "enable");
            }
            
            //var current = $(element).spinner("value");
			var current = jQuery(element).spinner("value");
            if (value !== current) {
                jQuery(element).spinner("value", value);
            }
		//}
    }
};

//----------------------- help method ------------------------

function showHelp() {
	//console.log("-------> showing help dialog",isHelpActive);

	if (!isHelpActive) {
		isHelpActive = true;
		helpType = "ayp_summative_assesment";
		//var active = jQuery("#tabs").tabs("option", "active");
		//help_scrollPosition = 'ayp_section_' + active;

		jQuery(".help").load("/ce-static-testedge/common/html/help.html", function() {
			//scrollTo('ayp_section_'+active);
			//console.log('ayp_section_' + active);
			//console.log("help called");
		});
      
	} else {
		isHelpActive = false;
		jQuery(".help").empty();
		
	}
}
function closeHelpSection() {
	//console.log("closing help section");
	isHelpActive = false;
	jQuery(".help").empty();
}